import React, { useState, useEffect } from 'react'
import { Form, Button, Input, Col, Table, Card, DatePicker, Upload, Icon, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import SearchBox from '@/components/SearchBox'
import { fetchSeckillInfoById, selectGoodsByIdOrNormId } from '@/services/marketCenter'
import moment from 'moment'
const { RangePicker } = DatePicker
import {router} from 'umi'


const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

const seckillGoodsConfig = props => {
  const { form, stores, location } = props
  const { getFieldDecorator } = form
  const [total, setTotalPage] = useState(0)
  const [seckillInfo, setSeckillInfo] = useState({
    activityName: '', // 活动名称
    goodsId: '',      // 活动商品 id
    normId: '',       // 活动商品 normId
    discount: '',
    provisions: 1,   // 输入限购数量
    startTime: '',    // 开始时间
    endTime: '',      // 开始时间
    seckillPrice: '', // 秒杀价格
    activityStock: 1, // 秒杀库存
    img:'',           // 秒杀图片
  })
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState('')

  const [seckillGoods, setSeckillGoods] = useState([])
  const [queryInfo, setQueryInfo] = useState({})
  const [param, setParam] = useState({
    pageNo: 1,
    pageSize: 10,
  })
  useEffect(() => {
    // setQueryInfo(location)
    location.query && location.query.id && _fetchSeckillInfoById(location.query.id)
    console.log(props)
  }, [])
  const _fetchSeckillInfoById = async (id) => {
    const res = await fetchSeckillInfoById({id: id})
    if (res.code == 0 && res.data) {
      setSeckillInfo(res.data)
      console.log(res)
      _selectGoodsByIdOrNormId(res.data)
    }
  }
  const _selectGoodsByIdOrNormId = async (data) => {
    let param = {
      listGoodsId: [data.goodsId],
    }
    if (data.listNormId) {
      param.listNormId = [data.normId]
    }
    const res = await selectGoodsByIdOrNormId(param)
    if (res.code == 0) {
      if (res.data.length) {
        setSeckillGoods(res.data)
      } else {
        setSeckillGoods([res.data])
      }
    }
  }


  const columns = [
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      key: '1',
      render: (v, r, i) => {
        console.log(r)
        return (<img src={v} style={{width: '40px', height: '40px'}} />)
      }
    },
    {
      title: '编号',
      dataIndex: 'goodsName',
      key: '2',
    },
    {
      title: "商品编号",
      dataIndex: "goodsCode",
      key: '3',
    },
    {
      title: "价格（元）",
      dataIndex: "shopPrice",
      key: "4"
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (v, r, i) => {
        return (<Button onClick={() => delCurrRecord(i)} type="danger">删除</Button>)
      }
    },
  ]
  const handleVisible = () => {

  }
  const dateFormat = 'YYYY-MM-DD HH:mm:ss'
  const pagination = { hideOnSinglePage: true }

  const handleSave = () => {
    console.log('新增 或者 跟新')
  }
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
        setLoading(false)
        setSeckillInfo({
          ...seckillInfo,
          img: imageUrl
        })
      })
    }
  }
  const uploadButton = (
    <div>
      <Icon type={loading ? 'loading' : 'plus'} />
      <div className="ant-upload-text">Upload</div>
    </div>
  )
  return (<PageHeaderWrapper title={location.query && location.query.id ? "编辑秒杀" : "新增秒杀"}>
    <Card>
      <Col span={24}>
        <Form.Item required label="活动名称" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`activityName`, {
            initialValue: seckillInfo.activityName
          })
            (<Input style={{width: '300px'}}/>)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item label="选择商品" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          <Button type="primary" onClick={{handleVisible}}>添加秒杀商品</Button>
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="已选商品" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          <Table pagination={pagination} rowKey={record => record.id} columns={columns} dataSource={seckillGoods} />
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="秒杀库存" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`activityStock`, {initialValue: seckillInfo.activityStock})
            (<Input style={{width: '150px'}}/>)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="秒杀价格" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`seckillPrice`, {initialValue: seckillInfo.seckillPrice})
            (<Input style={{width: '150px'}}/>)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="ID限购" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`provisions`, {initialValue: seckillInfo.provisions})
            (<Input style={{width: '150px'}}/>)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="开始时间" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`startTime`, {initialValue: moment(seckillInfo.startTime)})
            (<DatePicker format={dateFormat} />)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="结束时间" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`endTime`, {initialValue: moment(seckillInfo.endTime)})
            (<DatePicker format={dateFormat} />)}
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item required label="秒杀图片" labelCol={{ span: 3}} wrapperCol={{ span: 21 }}>
          {getFieldDecorator(`img`, {})
            (<Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {seckillInfo.img ? <img src={seckillInfo.img} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>)}
        </Form.Item>
      </Col>
      <Col span={21} offset={3}>
        <Button type="primary" onClick={handleSave}>提交</Button>
      </Col>
    </Card>
  </PageHeaderWrapper>)
}

export default Form.create()(seckillGoodsConfig)





